<template>
  <div class="order-detail-container">
    <el-card class="order-card">
      <!-- 订单基本信息 -->
      <div class="section order-info">
        <h2>订单信息</h2>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ order.order_number }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(order.status)">
              {{ getOrderStatusLabel(order.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ order.amount }}</el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getPaymentStatusTagType(order.payment_status)">
              {{ getPaymentStatusLabel(order.payment_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ order.customer_name }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ order.customer_phone }}</el-descriptions-item>
          <el-descriptions-item label="拍摄日期">{{ order.shooting_date }}</el-descriptions-item>
          <el-descriptions-item label="摄影师">{{
            order.photographer?.nickname
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 套餐信息 -->
      <div class="section package-info">
        <h2>套餐信息</h2>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="套餐名称">{{ order.package?.name }}</el-descriptions-item>
          <el-descriptions-item label="套餐价格">¥{{ order.package?.price }}</el-descriptions-item>
          <el-descriptions-item label="套餐内容">
            <div class="package-details">
              <div class="detail-section">
                <h4>套餐豪礼</h4>
                <div class="tags-container">
                  <el-tag
                    v-for="(item, index) in order.package?.package_gift"
                    :key="index"
                    class="detail-tag"
                  >
                    {{ item }}
                  </el-tag>
                </div>
              </div>

              <!-- 服务内容 -->
              <div class="detail-section">
                <h4>团队服务</h4>
                <ul class="service-list">
                  <li v-for="(service, index) in order.package?.team_service" :key="index">
                    <el-icon><Check /></el-icon>
                    {{ service }}
                  </li>
                </ul>
              </div>

              <!-- 拍摄产品 -->
              <div class="detail-section">
                <h4>影像产品</h4>
                <ul class="product-list">
                  <li v-for="(product, index) in order.package?.image_product" :key="index">
                    <el-icon><Picture /></el-icon>
                    {{ product }}
                  </li>
                </ul>
              </div>

              <!-- 注意事项 -->
              <div class="detail-section">
                <h4>温馨提示</h4>
                <ul class="tips-list">
                  <li v-for="(tip, index) in order.package?.tips" :key="index">
                    <el-icon><WarningFilled /></el-icon>
                    {{ tip }}
                  </li>
                </ul>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 增值服务选择 -->
      <div class="section additional-services">
        <h2>增值服务</h2>
        <el-form :model="additionalServices" label-width="120px">
          <!-- 底片选择 -->
          <el-form-item label="额外精修">
            <el-input-number
              v-model="additionalServices.extraPhotos"
              :min="0"
              :step="10"
              @change="calculateTotal"
              :disabled="order.status !== 1"
            />
            <span class="price-hint">（¥50/张）</span>
          </el-form-item>

          <!-- 相框选择 -->
          <el-form-item label="相框">
            <div class="frame-selection">
              <el-checkbox-group v-model="additionalServices.frames" @change="calculateTotal">
                <el-checkbox
                  v-for="frame in frameOptions"
                  :key="frame.id"
                  :label="frame.id"
                  class="frame-option"
                  :disabled="order.status !== 1"
                >
                  {{ frame.size }} (¥{{ frame.price }})
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>

          <!-- 相册选择 -->
          <el-form-item label="相册">
            <el-checkbox-group v-model="additionalServices.albums" @change="calculateTotal">
              <el-checkbox
                v-for="album in albumOptions"
                :key="album.id"
                :label="album.id"
                :disabled="order.status !== 1"
              >
                {{ album.size }} (¥{{ album.price }})
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 摆台选择 -->
          <el-form-item label="摆台">
            <el-checkbox-group v-model="additionalServices.tables" @change="calculateTotal">
              <el-checkbox
                v-for="table in tableOptions"
                :key="table.id"
                :label="table.id"
                :disabled="order.status !== 1"
              >
                {{ table.size }} (¥{{ table.price }})
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 其他服务 -->
          <el-form-item label="其他服务">
            <el-checkbox-group v-model="additionalServices.otherServices" @change="calculateTotal">
              <el-checkbox label="video" :disabled="order.status !== 1"
                >微电影拍摄 (¥2000)</el-checkbox
              >
              <el-checkbox label="drone" :disabled="order.status !== 1"
                >航拍服务 (¥1000)</el-checkbox
              >
              <el-checkbox label="sameday" :disabled="order.status !== 1"
                >当天快修 (¥500)</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>

      <!-- 费用明细 -->
      <div class="section price-summary">
        <h2>费用明细</h2>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="套餐基础价格">
            ¥{{ order.package?.price || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="额外精修费用">
            ¥{{ additionalCosts.extraPhotos }}
          </el-descriptions-item>
          <el-descriptions-item label="相框费用">
            ¥{{ additionalCosts.frames }}
          </el-descriptions-item>
          <el-descriptions-item label="其他服务费用">
            ¥{{ additionalCosts.others }}
          </el-descriptions-item>
          <el-descriptions-item label="总计金额" class="total-amount">
            ¥{{ totalAmount }}
          </el-descriptions-item>
          <el-descriptions-item label="定金" class="total-amount">
            ¥{{ order.deposit }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 底部操作按钮 -->
      <div class="actions">
        <el-button @click="goBack">返回</el-button>
        <el-button
          type="primary"
          v-if="order.status === 1"
          @click="handleConfirm"
          :loading="submitting"
        >
          确认订单
        </el-button>
        <el-button
          type="primary"
          v-if="order.status === 2 && order.payment_status === 1"
          @click="handlePayDeposit"
        >
          支付定金
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderDetail, confirmOrder } from '@/api/order'
import type { Order, AdditionalServices } from '@/types/order'
const route = useRoute()
const router = useRouter()
const submitting = ref(false)

// 订单数据
const order = ref<Order>({} as Order)

// 相框选项
const frameOptions = [
  { id: 1, size: '8寸相框', price: 100 },
  { id: 2, size: '12寸相框', price: 200 },
  { id: 3, size: '16寸相框', price: 300 },
  { id: 4, size: '20寸相框', price: 500 },
]

const albumOptions = [
  { id: 1, size: '10寸相册', price: 100 },
  { id: 2, size: '12寸相册', price: 200 },
  { id: 3, size: '16寸相册', price: 300 },
]

const tableOptions = [
  { id: 1, size: '10寸摆台', price: 100 },
  { id: 2, size: '14寸摆台', price: 200 },
  { id: 3, size: '18寸摆台', price: 300 },
]

// 增值服务选择
const additionalServices = reactive<AdditionalServices>({
  extraPhotos: 0, // 额外底片数量
  frames: [], // 选择的相框
  albums: [], // 选择的相册
  tables: [], // 选择的摆台
  otherServices: [], // 其他服务
})

// 格式化金额的工具函数
const formatPrice = (price: number): number => {
  return Number(price.toFixed(2))
}

// 计算各项额外费用
const additionalCosts = computed(() => {
  const extraPhotos = additionalServices.extraPhotos * 50

  const frames = formatPrice(
    additionalServices.frames.reduce((total, frameId) => {
      const frame = frameOptions.find((f) => f.id === frameId)
      return total + (frame?.price || 0)
    }, 0),
  )

  const others = formatPrice(
    additionalServices.otherServices.reduce((total, service) => {
      const prices: Record<string, number> = {
        video: 2000,
        drone: 1000,
        sameday: 500,
      }
      return total + (prices[service] || 0)
    }, 0),
  )

  const album = formatPrice(
    additionalServices.albums.reduce((total, albumId) => {
      const album = albumOptions.find((a) => a.id === albumId)
      return total + (album?.price || 0)
    }, 0),
  )

  const table = formatPrice(
    additionalServices.tables.reduce((total, tableId) => {
      const table = tableOptions.find((t) => t.id === tableId)
      return total + (table?.price || 0)
    }, 0),
  )

  return {
    extraPhotos,
    frames,
    others,
    album,
    table,
  }
})

// 计算总金额
const totalAmount = computed(() => {
  const basePrice = Number(order.value.package?.price) || 0
  const { extraPhotos, frames, others, album, table } = additionalCosts.value
  return basePrice + extraPhotos + frames + others + album + table
})

// 获取订单状态标签类型
const getOrderStatusType = (status: number) => {
  const types: Record<number, string> = {
    1: 'warning',
    2: 'primary',
    3: 'success',
    4: 'info',
    5: 'danger',
  }
  return types[status]
}

// 获取订单状态标签文本
const getOrderStatusLabel = (status: number) => {
  const labels: Record<number, string> = {
    1: '待确认',
    2: '已确认',
    3: '后期处理中',
    4: '已完成',
    5: '已取消',
  }
  return labels[status]
}

// 获取支付状态标签类型
const getPaymentStatusTagType = (status: number) => {
  const types: Record<number, string> = {
    1: 'danger',
    2: 'warning',
    3: 'success',
  }
  return types[status]
}

// 获取支付状态标签文本
const getPaymentStatusLabel = (status: number) => {
  const labels: Record<number, string> = {
    1: '未支付',
    2: '部分支付',
    3: '已支付',
  }
  return labels[status]
}

// 计算总价
const calculateTotal = () => {
  // 总价会通过计算属性自动更新
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 确认选择
const handleConfirm = async () => {
  submitting.value = true
  try {
    await ElMessageBox.confirm(
      '确认订单信息无误，即将跳转页面去支付定金，定金支付后不退哦～',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    await confirmOrder({
      orderId: order.value.id,
      additionalServices,
      totalAmount: totalAmount.value,
    })

    ElMessage.success('订单已确认')
    router.push(`/payment/${order.value.id}`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

const handlePayDeposit = async () => {
  router.push(`/payment/${order.value.id}`)
}

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    const { data } = await getOrderDetail(Number(route.params.id))
    order.value = data.data
    if (data.data.additional_services) {
      additionalServices.extraPhotos = data.data.additional_services.extraPhotos
      additionalServices.frames = data.data.additional_services.frames.map(Number)
      additionalServices.albums = data.data.additional_services.albums.map(Number)
      additionalServices.tables = data.data.additional_services.tables.map(Number)
      additionalServices.otherServices = data.data.additional_services.otherServices as string[]
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  }
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.section {
  margin-bottom: 30px;
}

.section h2 {
  margin-bottom: 20px;
  font-size: 18px;
  color: #333;
}

.package-details {
  padding: 10px;
}

.detail-group {
  margin-bottom: 20px;
}

.detail-group h4 {
  margin-bottom: 10px;
  color: #666;
}

.detail-group ul {
  list-style: none;
  padding-left: 0;
}

.detail-group li {
  margin-bottom: 5px;
}

.price-hint {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}

.frame-selection {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.frame-option {
  margin-right: 20px;
}

.total-amount :deep(.el-descriptions-item__content) {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.detail-description {
  margin: 20px 0;
  line-height: 1.6;
  color: #666;
}

.detail-section {
  margin: 20px 0;
}

.detail-section h4 {
  margin-bottom: 15px;
  font-size: 18px;
  color: #333;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.detail-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.service-list,
.product-list,
.tips-list {
  list-style: none;
  padding: 0;
}

.service-list li,
.product-list li,
.tips-list li {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.service-list .el-icon {
  color: #67c23a;
}

.product-list .el-icon {
  color: #4073ff;
}

.tips-list .el-icon {
  color: #fab641;
}
</style>
